package com.hyacinth.lotterysystem.common.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.hyacinth.lotterysystem.common.config.EmailConfig;
import com.hyacinth.lotterysystem.common.constant.Constants;
import com.hyacinth.lotterysystem.dao.entity.WinningRecordDO;
import com.hyacinth.lotterysystem.service.enums.ActivityPrizeTiersEnum;
import jakarta.annotation.Resource;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

import static com.hyacinth.lotterysystem.common.constant.Constants.VALID_TIME;

@Component
public class EmailUtil {
    private static final Logger logger = LoggerFactory.getLogger(EmailUtil.class);

    @Resource
    private EmailConfig emailConfig;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 发送邮件
     */
    public void sendEmail(String toEmail, String subject, String msg) throws EmailException {
        SimpleEmail email = new SimpleEmail();
        //qq：qq邮件服务器的端口号
        email.setSslSmtpPort(emailConfig.getPort());
        email.setHostName(emailConfig.getHost());
        email.setAuthentication(emailConfig.getUsername(), emailConfig.getPassword());
        email.setCharset(emailConfig.getCharset());
        email.setFrom(emailConfig.getFrom());
        email.setSSLOnConnect(true);
        //1、从文件把所有的qq邮箱读取出来
        //2、存储到一个数据结构当中
        //3、String email = 数据结构当中取一个
        try {
            email.addTo(toEmail);
            email.setSubject(subject);
            email.setMsg(msg);
            email.send();
        } catch (EmailException e) {
            throw new EmailException("发送邮件失败: " + e.getMessage());
        }
    }

    /**
     * 发送验证码
     *
     * @param email
     */
    public void sendEmailVerificationCode(String email) throws EmailException {
        String code = RandomUtil.randomNumbers(4);
        redisUtil.set(Constants.REDIS_KEY_EMAIL_CODE_PREFIX + email, code, VALID_TIME);
        String sub = "【抽奖系统】登录验证码";
        String msg = "您的登录验证码是 " + code + ",5分钟内有效, 请勿向任何人提供此验证码。";
        sendEmail(email, sub, msg);
    }

    public void senWinningRecord(List<WinningRecordDO> winningRecordDOList) throws EmailException {
        if (winningRecordDOList == null) {
            logger.info("中奖记录列表为空，不需要发邮件");
            return;
        }
        for (WinningRecordDO winningRecordDO : winningRecordDOList) {
            String context = "Hi，" + winningRecordDO.getWinnerName() + "。恭喜你在"
                    + winningRecordDO.getActivityName() + "活动中获得"
                    + Objects.requireNonNull(ActivityPrizeTiersEnum.forName(winningRecordDO.getPrizeTier())).getMessage()
                    + "：" + winningRecordDO.getPrizeName() + "。获奖时间为"
                    + DateUtil.formatTime(winningRecordDO.getWinningTime()) + "，请尽快领 取您的奖励！";
            // 发送邮件
            logger.info("正在给" + winningRecordDO.getWinnerEmail() + "发送邮件");
            sendEmail(winningRecordDO.getWinnerEmail(), "中奖通知", context);
        }
    }
}
